import java.util.Random;
import javax.swing.JOptionPane;

/**
 * Used to create a user in the spreadsheet database. Looks for db.dat file for database password.
 * Prompts for user name and will generate your public and private key files. Do not lose them!!!
 * 
 * User cannot be created if an existing user with that name exists.
 * 
 * @author Andrew Gifford
 *
 */
public class CreateUser {

	public static void main(String[] args) throws Exception
	{

		if(args.length == 0){
			JOptionPane.showMessageDialog(null, "Usage: java CreateUser password", "Create User",JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		if(args[0] == null || args[0].equals("")){
			JOptionPane.showMessageDialog(null, "Usage: java CreateUser password", "Create User",JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}

		String temp = JOptionPane.showInputDialog(null, "Please enter your desired user name.", "Enter Username Here.");
		if(temp == null || temp.equals("")){
			JOptionPane.showMessageDialog(null, "Didn't Create User.", "Create User",JOptionPane.DEFAULT_OPTION);
			System.exit(0);
		}
		String username = temp.toLowerCase().trim();

		if(username.length() > 20){
			JOptionPane.showMessageDialog(null, "Didn't Create User...\nA username must be less than 20 characters.", "ERROR--Create User",JOptionPane.DEFAULT_OPTION);
			System.exit(0);
		}
			
		String passkey = "";
		char character;
		Random gen = new Random();
		//Makes a random string to use as a password
		for(int i = 0; i < 15; i++)
		{
			//Flip a coin...uppercase or lowercase characters
			if(gen.nextInt(2) == 0)
			{
				character = (char)(gen.nextInt(10) + 65);
				passkey = passkey + character;
			}
			else
			{
				character = (char)(gen.nextInt(10) + 97);
				passkey = passkey + character;
			}
		}


		//then add to database
		DatabaseUtil.setDBPassword(args[0]);
		if(!DatabaseUtil.canConnect()){
			JOptionPane.showMessageDialog(null, "Didn't Create User.", "Create User",JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		if(DatabaseUtil.userInDB(username)){
			JOptionPane.showMessageDialog(null, "Sorry, a user with that name already exists.", ":-(",JOptionPane.ERROR_MESSAGE);
		}
		else{
			KeyGen.getKeys(passkey,512,username,"RSA");
			DatabaseUtil.addUser(username, username + ".pub");
			JOptionPane.showMessageDialog(null, "User successfully added.", "SUCCESS!",JOptionPane.DEFAULT_OPTION);
		}
		
	}
}
